package com.idanchuang.component.logback.tool;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日志解析工具
 * @author yjy
 * @date 2020/8/26 17:30
 **/
public class LogParser {

    protected static Pattern LOG_PATTERN = Pattern.compile("(\\d+-\\d+-\\d+\\s\\d+:\\d+:\\d+)\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([^\\]]+)\\s\\]\\s\\[\\s([-|\\d]+)\\s\\](?:\\s\\[\\s([^\\]]+)\\s\\]){0,1}\\s-\\s(.*)");

    protected static int GROUP_COUNT = 14;

    /**
     * 解析日志
     * @param log 原始日志
     * @return 日志实体
     */
    public static LogData parse(String log) {
        Matcher matcher = LOG_PATTERN.matcher(log);
        if (matcher.find() && matcher.groupCount() == GROUP_COUNT) {
            LogData logData = new LogData();
            logData.setLogTime(matcher.group(1));
            logData.setLogLevel(matcher.group(2));
            logData.setAppId(matcher.group(3));
            logData.setAppVersion(matcher.group(4));
            logData.setAppGroup(matcher.group(5));
            logData.setAddress(matcher.group(6));
            logData.setTraceId(matcher.group(7));
            logData.setThread(matcher.group(8));
            logData.setFile(matcher.group(9));
            logData.setMethod(matcher.group(10));
            logData.setUrl(matcher.group(11));
            String duration = matcher.group(12);
            logData.setDuration(!"-".equals(duration) ? Integer.valueOf(duration) : null);
            logData.setKeyword(matcher.group(13));
            logData.setContent(matcher.group(14));
            return logData;
        }
        return null;
    }

//    public static void main(String[] args) {
//        String log = "2020-08-25 10:25:41 [ INFO ] [ EXAMPLE-CONSUMER ] [ -1 ] [ default ] [ 172.20.50.63:10100 ] [ TID: N/A ] [ apply-worker ] [ GeneralSeqIdServiceImpl.java:159 ] [ lambda$fillReady$0 ] [ - ] [ 177127 ] [ 关键词x ] - fileReady ok > appId: example_consumer, tableName: test";
//        LogData logData = LogParser.parse(log);
//        System.out.println(logData);
//    }

}
